<template>
  <page-wrap>
    <div class="mb-10px">
      <a-button type="primary" @click="addAction()">新增</a-button>
    </div>
    <table-wrap
      :columns="tableColumns"
      :data="dataList"
      :pagination="false"
      default-expand-all-rows
      node-key="id"
      :loading="loading"
      @register="tableRegister"
    />
  </page-wrap>

  <modal-dialog v-model="dialogVisible" :title="dialogTitle" width="460">
    <AddForm
      v-if="actionType === 'add'"
      ref="addFormRef"
      :data="dataModel"
      :tree-list="dataList || []"
      :current-parent-id="currentParentId"
    />
    <EditForm
      v-if="actionType === 'edit'"
      ref="editFormRef"
      :data="dataModel"
      :tree-list="dataList || []"
    />
    <template #footer>
      <a-button
        v-if="actionType === 'add'"
        type="primary"
        :loading="saveLoading"
        @click="save()"
      >
        保存
      </a-button>
      <a-button
        v-if="actionType === 'edit'"
        type="primary"
        :loading="saveLoading"
        @click="update()"
      >
        保存
      </a-button>
      <a-button @click="dialogVisible = false">关闭</a-button>
    </template>
  </modal-dialog>
</template>

<script setup lang="tsx">
  import { Link } from '@arco-design/web-vue';

  import {
    listApi,
    getApi,
    saveApi,
    updateApi,
    removeApi,
  } from '@/api/system/organization';
  import { OrganizationVO } from '@/api/system/organization/types';
  import { useTable } from '@/hooks/table';

  import AddForm from './components/add-form.vue';
  import EditForm from './components/edit-form.vue';

  const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
      return await listApi();
    },
    fetchDelApi: async () => {
      const res = await removeApi(unref(currentId));
      return !!res;
    },
  });

  const { dataList, loading } = tableState;
  const { getList, delList } = tableMethods;

  const tableColumns = reactive<TableColumn[]>([
    {
      field: 'index',
      title: '序号',
      type: 'index',
    },
    {
      field: 'code',
      title: '编码',
    },
    {
      field: 'name',
      title: '名称',
    },
    {
      field: 'sequence',
      title: '排序',
    },
    {
      field: 'state',
      title: '状态',
      width: 200,
      type: 'enumTag',
      enumName: 'State',
    },
    {
      field: 'action',
      title: '操作',
      width: 200,
      render: (data: any) => {
        const row = data.record as OrganizationVO;
        return (
          <>
            {row.depth < 3 && (
              <Link onClick={() => addAction(row.id, row.depth)}>新增</Link>
            )}
            <Link onClick={() => editAction(row.id)}>编辑</Link>
            <Link onClick={() => delAction(row.id)}>删除</Link>
          </>
        );
      },
    },
  ]);

  const dataModel = ref<any>();

  const currentId = ref<string>();
  const currentParentId = ref<string>();
  const currentDepth = ref(0);

  const addFormRef = ref<ComponentRef<typeof AddForm>>();
  const editFormRef = ref<ComponentRef<typeof EditForm>>();

  const actionType = ref('');
  const dialogTitle = ref('');
  const dialogVisible = ref(false);
  const saveLoading = ref(false);

  // 新增
  const addAction = (id?: string, depth?: number) => {
    dataModel.value = undefined;
    currentParentId.value = id;
    currentDepth.value = depth ?? 0;
    actionType.value = 'add';
    dialogTitle.value = '新增';
    dialogVisible.value = true;
  };

  const save = async () => {
    const addForm = unref(addFormRef);
    const formData = await addForm?.submit();
    if (formData) {
      saveLoading.value = true;
      try {
        const res = await saveApi(formData as OrganizationVO);
        if (res) {
          getList(false);
          dialogVisible.value = false;
        }
      } finally {
        saveLoading.value = false;
      }
    }
  };

  // 编辑
  const editAction = async (id: string) => {
    dataModel.value = await getApi(id);
    actionType.value = 'edit';
    dialogTitle.value = '编辑';
    dialogVisible.value = true;
  };

  const update = async () => {
    const editForm = unref(editFormRef);
    const formData = await editForm?.submit();
    if (formData) {
      saveLoading.value = true;
      try {
        const res = await updateApi(formData as OrganizationVO);
        if (res) {
          getList();
          dialogVisible.value = false;
        }
      } finally {
        saveLoading.value = false;
      }
    }
  };

  // 删除
  const delAction = async (id: string) => {
    currentId.value = id;
    await delList(1).finally(() => {});
  };
</script>
